import { wrapperToken } from '@/utils'
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export default function tableHooks(getTableData, formLimit = 10) {
  const searchForm = ref({
    page: 1,
    limit: formLimit
  })
  const total = ref(0)
  const handleSearch = (callbackFunction = getTableData) => {
    searchForm.value.page = 1
    callbackFunction()
  }
  const handleReset = (val = {}, callbackFunction = getTableData) => {
    searchForm.value = {
      page: 1,
      limit: formLimit,
      ...val
    }
    callbackFunction()
  }

  // 表格序号
  const serialNumber = index => (searchForm.value.page - 1) * searchForm.value.limit + (index + 1)
  // 多选
  const multipleSelection = ref([])
  const handleSelectionChange = val => {
    multipleSelection.value = val
  }
  // 分页
  const handlePageChange = (type, value) => {
    searchForm.value[type] = value
    if (type === 'limit') {
      searchForm.value.page = 1
    }
    getTableData()
  }
  // 批量删除
  const handleBatchDelete = async (
    deleteApi,
    deleteField,
    message = '是否删除选中的数据?',
    info = '删除成功',
    callbackFunction = getTableData
  ) => {
    if (multipleSelection.value?.length === 0) {
      ElMessage.warning('请选择要删除的数据')
    } else {
      await handleDelete(
        deleteApi,
        multipleSelection.value.map(el => el[deleteField]),
        message,
        info,
        callbackFunction
      )
    }
  }
  // 删除
  const handleDelete = (
    deleteApi,
    deleteIdParams,
    message = '是否删除选中的数据?',
    info = '删除成功',
    callbackFunction = getTableData
  ) => {
    ElMessageBox.confirm(message, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const res = await deleteApi(deleteIdParams)
        if (res.code === 200 || res.code === 0) {
          ElMessage.success(info)
        }
        await callbackFunction() // 删除完之后的回调函数
      })
      .catch(() => {})
  }
  // 导出
  const handleExportExcel = async (
    downloadApi,
    formData,
    callbackFunction = () => {},
    name = ''
  ) => {
    axios
      .post(`${import.meta.env.VITE_BASE_API}${downloadApi}`, formData, {
        responseType: 'blob',
        headers: {
          token: wrapperToken.getToken()
        }
      })
      .then(res => {
        const blob = new Blob([res.data], {
          type: 'applicationnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
        })
        let fileName = res.headers['content-disposition']
        if (fileName) {
          fileName = decodeURIComponent(fileName)
        } else {
          fileName = `${name || '导出数据'}.xlsx`
        }
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = `${fileName}` // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
        callbackFunction()
        ElMessage.success('导出成功')
      })
      .catch(error => {
        ElMessage.error(error)
      })
  }
  // 导入
  const handleImportExcel = (importApi, params = {}, callbackFunction = getTableData) => {
    const element = document.getElementById('global-upload')
    if (element) {
      element.click()
      element.onchange = e => {
        const inputElement = e.target as HTMLInputElement
        const { files } = inputElement
        if (files && files[0]) {
          const formDataParams = new FormData()
          formDataParams.append('file', files[0]) // 通过append向form对象添加数据
          Object.keys(params).forEach(key => {
            formDataParams.append(key, params[key])
          })
          axios
            .post(`${import.meta.env.VITE_BASE_API}${importApi}`, formDataParams, {
              headers: {
                token: wrapperToken.getToken()
              }
            })
            .then(response => {
              const res = response.data
              if (res.code === 0 || res.code === 200) {
                callbackFunction()
                ElMessage.success('上传成功')
              } else {
                let msg = null
                if (res.data) {
                  msg = res.data?.join('、') || ''
                }
                ElMessage.error(res.msg + msg)
              }
              inputElement.value = ''
            })
            .catch(error => {
              ElMessage.error(error)
            })
        }
      }
    }
  }
  const getBase64 = async file =>
    new Promise((resolve, reject) => {
      const reader = new FileReader()
      let imgResult: string | ArrayBuffer | null = null
      reader.readAsDataURL(file)
      reader.onload = function () {
        imgResult = reader.result
      }
      reader.onerror = function (error) {
        reject(error)
      }
      reader.onloadend = function () {
        resolve(imgResult)
      }
    })

  return {
    searchForm,
    multipleSelection,
    total,
    getBase64,
    serialNumber,
    handleSearch,
    handleReset,
    handleDelete,
    handleBatchDelete,
    handleExportExcel,
    handleImportExcel,
    handlePageChange,
    handleSelectionChange
  }
}
